package com.escapeicon.bigevent.controller;

import com.escapeicon.bigevent.pojo.entity.User;
import com.escapeicon.bigevent.pojo.vo.ResultVO;
import com.escapeicon.bigevent.service.UserService;
import com.escapeicon.bigevent.utils.JwtUtil;
import com.escapeicon.bigevent.utils.Md5Util;
import com.escapeicon.bigevent.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/register")
    public ResultVO register(@Pattern(regexp = "^\\S{5,16}$") String username,@Pattern(regexp = "^\\S{5,16}$") String password) {
        User user = userService.findByUserName(username);
        if (user != null) {
            //用户名 被占用
            return ResultVO.error("用户名已被占用");
        } else {
            //用户名 没被占用
            userService.register(username, password);
            return ResultVO.success();
        }
    }

    @PostMapping("/login")
    public ResultVO<String> login(String username, String password) {
        User user = userService.findByUserName(username);
        if (user != null) {
            //用户存在
            if (user.getPassword().equals(Md5Util.getMD5String(password))) {
                Map<String, Object> map = new HashMap<>();
                map.put("id",user.getId());
                map.put("username",user.getUsername());

                //生成令牌
                String token = JwtUtil.genToken(map);

                // 向 redis 中存储一份 token
                ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
                operations.set(token,token,1, TimeUnit.HOURS);// 存储 token 并设置1小时过期时间

                //密码匹配
                return ResultVO.success(token);
            }else {
                //密码错误
                return ResultVO.error("密码错误");
            }
        }
        return ResultVO.error("用户名不存在");
    }

    @GetMapping("/userInfo")
    public ResultVO<User> getUser(){
        Map<String,Object> claim = ThreadLocalUtil.get();
        String username = (String) claim.get("username");

        User user = userService.findByUserName(username);
        if (user != null) {
            return ResultVO.success(user);
        }
        return ResultVO.error("不存在该用户");
    }

    @PutMapping("/update")
    public ResultVO update(@RequestBody @Validated User user){
        userService.updateUser(user);
        return ResultVO.success();
    }

    @PatchMapping("/updateAvatar")
    public ResultVO updateAvatar(@RequestParam @URL String avatarUrl) {
        userService.updateAvatar(avatarUrl);
        return ResultVO.success();
    }

    @PatchMapping("/updatePwd")
    public ResultVO updatePwd(@RequestBody Map<String,String> map,@RequestHeader("Authorization") String token){
        // 1. 获取新旧密码
        String oldPwd = map.get("old_pwd");
        String newPwd = map.get("new_pwd");
        String rePwd = map.get("re_pwd");

        // 2. 手动校验
        // 判空
        if (!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)) {
            return ResultVO.error("缺少必要的参数!");
        }
        // 同数据库验证旧密码
        Map<String, Object> userInfo = (Map<String, Object>) ThreadLocalUtil.get();
        String username = (String) userInfo.get("username");
        User user = userService.findByUserName(username);
        if (!Md5Util.getMD5String(oldPwd).equals(user.getPassword())) {
            return ResultVO.error("旧密码不正确");
        }
        // 验证两次输入密码是否相同
        if (!newPwd.equals(rePwd)) {
            return ResultVO.error("两次密码输入不相同");
        }
        // 验证新密码与旧密码是否相同
        if (newPwd.equals(oldPwd)) {
            return ResultVO.error("新密码不能与旧密码相同");
        }

        // 3.更新数据
        userService.updatePwd(newPwd);

        // 删除 redis 中已存在的 token
        stringRedisTemplate.delete(token);

        return ResultVO.success();
    }
}
